using System.IO;
using System.Xml;
using System.Xml.Schema;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace XmlFieldType
{
    public class SPFieldXml : SPFieldXmlBase
    {

        private const string RENDER_XML = "RenderXml";
        private const string SCHEMA_XML = "ValidationSchemaXml";

        public SPFieldXml(SPFieldCollection fields, string fieldName)
            : base(fields, fieldName)
        {
        }

        public SPFieldXml(SPFieldCollection fields, string typeName, string displayName)
            : base(fields, typeName, displayName)
        {
        }

        public override BaseFieldControl FieldRenderingControl
        {
            get
            {
                BaseFieldControl fieldControl = new XmlField(this);

                fieldControl.FieldName = InternalName;

                return fieldControl;
            }
        }

        public string ValidationSchemaXml
        {
            get
            {
                return this.GetCustomProperty(SCHEMA_XML) + "";
            }
            set
            {
                this.SetCustomProperty(SCHEMA_XML, value);
            }
        }

        public string RenderXml
        {
            get
            {
                return this.GetCustomProperty(RENDER_XML) + "";
            }
            set
            {
                this.SetCustomProperty(RENDER_XML, value);
            }
        }

        public override string GetValidatedString(object value)
        {
            string validated=base.GetValidatedString(value);

            if (!string.IsNullOrEmpty(this.ValidationSchemaXml))
            {
                try
                {
                    StringReader rdr = new StringReader(this.ValidationSchemaXml);

                    XmlSchema schema = XmlSchema.Read(rdr, null);

                    XmlReaderSettings settings = new XmlReaderSettings()
                    {
                        ValidationType = ValidationType.Schema
                    };

                    settings.Schemas.Add(schema);

                    StringReader xmlRdr = new StringReader(value.ToString());
                    XmlReader xmlReader = XmlReader.Create(xmlRdr, settings);


                    using (xmlReader)
                    {

                        while (xmlReader.Read())
                        {
                        }
                    }

                    return validated;
                }
                catch (XmlException ex)
                {
                    //Validation failed
                    throw new SPFieldValidationException(string.Format("{0} has an invalid value. {1}", this.Title, ex.Message), ex);
                }
            }
            else
            {
                return validated;
            }

        }

    }

}
